import { api, tokenManager } from './request';

// 登录请求
export interface LoginRequest {
  username: string;
  password: string;
}

// 登录响应
export interface LoginResponse {
  token: string;
  refreshToken?: string;
  expiresIn: number;
  userInfo: AdminUserInfo;
}

// 管理员用户信息
export interface AdminUserInfo {
  id: number;
  username: string;
  nickname?: string;
  email?: string;
  role: string;
  permissions?: string[];
  avatar?: string;
  lastLoginTime?: string;
}

// 修改密码请求
export interface ChangePasswordRequest {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

// 认证API
export const authApi = {
  // 管理员登录
  login(data: LoginRequest): Promise<LoginResponse> {
    return api.post('/api/auth/admin/login', data).then((response) => {
      // 登录成功后保存token
      if (response.token) {
        tokenManager.setToken(response.token);
      }
      return response;
    });
  },

  // 退出登录
  logout(): Promise<void> {
    return api.post('/api/auth/logout').then(() => {
      // 清除本地token
      tokenManager.removeToken();
    }).catch(() => {
      // 即使后端请求失败，也要清除本地token
      tokenManager.removeToken();
    });
  },

  // 刷新token
  refreshToken(refreshToken: string): Promise<{ token: string; expiresIn: number }> {
    return api.post('/api/auth/refresh', { refreshToken }).then((response) => {
      if (response.token) {
        tokenManager.setToken(response.token);
      }
      return response;
    });
  },

  // 获取当前用户信息
  getCurrentUser(): Promise<AdminUserInfo> {
    return api.get('/api/auth/me');
  },

  // 修改密码
  changePassword(data: ChangePasswordRequest): Promise<void> {
    return api.post('/api/auth/change-password', data);
  },

  // 验证token有效性
  validateToken(): Promise<boolean> {
    return api.get('/api/auth/validate').then(() => true).catch(() => false);
  },
};

export default authApi;